package cn.ac.aircas.web.controller.common;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;

import cn.ac.aircas.common.annotation.Anonymous;
import cn.ac.aircas.framework.config.OAuth2Config;
import cn.ac.aircas.common.utils.http.HttpUtils;
import cn.ac.aircas.framework.config.properties.SocialLoginConfigProperties;
import com.alibaba.fastjson2.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.*;
import com.google.code.kaptcha.Producer;
import cn.ac.aircas.common.config.DefectedConfig;
import cn.ac.aircas.common.constant.CacheConstants;
import cn.ac.aircas.common.constant.Constants;
import cn.ac.aircas.common.core.domain.AjaxResult;
import cn.ac.aircas.common.core.redis.RedisCache;
import cn.ac.aircas.common.utils.sign.Base64;
import cn.ac.aircas.common.utils.uuid.IdUtils;
import cn.ac.aircas.system.service.ISysConfigService;

/**
 * 验证码操作处理
 *
 * @author defected
 */
@RestController
public class CaptchaController {
    private final Logger log = LoggerFactory.getLogger(CaptchaController.class);
    @Resource(name = "captchaProducer")
    private Producer captchaProducer;

    @Resource(name = "captchaProducerMath")
    private Producer captchaProducerMath;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    OAuth2Config oAuth2Config;

    /**
     * 生成验证码
     */
    @GetMapping("/captchaImage")
    public AjaxResult getCode(HttpServletResponse response) throws IOException {
        AjaxResult ajax = AjaxResult.success();
        Map<String,Object> resData = new HashMap<>();
        boolean captchaEnabled = configService.selectCaptchaEnabled();
        resData.put("captchaEnabled", captchaEnabled);
        if (!captchaEnabled) {
            return ajax;
        }

        // 保存验证码信息
        String uuid = IdUtils.simpleUUID();
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;

        String capStr, code = null;
        BufferedImage image = null;

        // 生成验证码
        String captchaType = DefectedConfig.getCaptchaType();
        if ("math".equals(captchaType)) {
            String capText = captchaProducerMath.createText();
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            image = captchaProducerMath.createImage(capStr);
        } else if ("char".equals(captchaType)) {
            capStr = code = captchaProducer.createText();
            image = captchaProducer.createImage(capStr);
        }

        redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        // 转换流信息写出
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", os);
        } catch (IOException e) {
            return AjaxResult.error(e.getMessage());
        }

        resData.put("uuid", uuid);
        resData.put("img", Base64.encode(os.toByteArray()));
        resData.put("loginOther",Boolean.valueOf(configService.selectConfigByKey("sys.user.OtherLogin")));
        ajax.put("data",resData);
        return ajax;
    }

    @Anonymous
    @GetMapping("/getWxCode")
    public String getWxCode() {
        SocialLoginConfigProperties socialLoginConfigProperties = oAuth2Config.getType().get("gitee");
        JSONObject param = new JSONObject();
        param.put("expire_seconds",7200);
        param.put("action_name","QR_STR_SCENE");

        String accessToken = redisCache.hasKey("access_token") ? redisCache.getCacheObject("access_token").toString() : null;
        String ticket = redisCache.hasKey("ticket") ? redisCache.getCacheObject("ticket").toString() : null;


        if (ticket != null) {
            return "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + ticket;
        } else if (accessToken != null) {
            String ticketUrl = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + accessToken;
            JSONObject ticketJson = JSONObject.parseObject(HttpUtils.sendPost(ticketUrl,param.toString()));
            ticket = ticketJson.getString("ticket");
            redisCache.setCacheObject("ticket",ticket,7200,TimeUnit.SECONDS);
            return "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + ticket;
        } else {
            String baseUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential" +
                    "&appid=" + socialLoginConfigProperties.getClientId() +
                    "&secret=" + socialLoginConfigProperties.getClientSecret();
            JSONObject accessJson = JSONObject.parseObject(HttpUtils.sendGet(baseUrl));
            accessToken = accessJson.getString("access_token");
            redisCache.setCacheObject("accessToken",accessToken,7200,TimeUnit.SECONDS);

            String ticketUrl = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=" + accessToken;
            JSONObject ticketJson = JSONObject.parseObject(HttpUtils.sendPost(ticketUrl,param.toString()));
            ticket = ticketJson.getString("ticket");
            redisCache.setCacheObject("ticket",ticket,7200,TimeUnit.SECONDS);

            return "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" + ticket;
        }
    }
}
